import React, {useState} from "react";
import {Button, Grid} from "@material-ui/core";
import {AddRounded} from "@material-ui/icons";

import {EnhancedTable, Toolbar} from "../../shared/components";
import {getRoutes} from "../../shared/services/data.service";

const ViewAllRoute = ({onAdd, onRowClick, ...props}) => {
    const [routes, setRoutes] = useState([]);

    const getRouteList = () => (
        new Promise((resolve, reject) => {
            getRoutes().then(res => {
                const routeList = res.data.map(route => ({
                    ...route,
                    source: route.source_address.address1,
                    destination: route.destination_address.address1
                }));
                setRoutes(routeList);
                resolve(routeList);
            }).catch(error => reject(error));
        })
    );

    return (
        <Grid container spacing={4}>
            <Toolbar
                title="Routes"
                actions={<React.Fragment>
                    <Button
                        variant="contained"
                        color="primary"
                        startIcon={<AddRounded/>}
                        onClick={onAdd}
                    >
                        Add Route
                    </Button>
                </React.Fragment>}
            />

            <Grid item xs={12}>
                <EnhancedTable
                    title={"Route Stops"}
                    schema={[
                        {id: 'id', label: '', hidden: true},
                        {id: 'route_code', label: 'Code', sort: true},
                        {id: 'name', label: 'Name', sort: true},
                        {id: 'source', label: 'Source', sort: true},
                        {id: 'destination', label: 'Destination', sort: true},
                        {id: 'std_distance_cycle', label: 'Distance Cycle', sort: true},
                        {id: 'std_cycle_hours', label: 'Cycle hours', sort: true}
                    ]}
                    async={{loading: true, loadingData: getRouteList}}
                    pagination={routes.length > 5}
                    onRowClick={onRowClick}
                />
            </Grid>
        </Grid>
    );
};

export default ViewAllRoute;
